package org.lop.demo.web;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.StaleStateException;
import org.lop.demo.domain.DemoVersionEntity;
import org.lop.demo.service.DemoVersionService;
import org.lop.modules.data.mapper.QueryFilter;
import org.lop.modules.data.mapper.QueryFilterHandler;
import org.lop.modules.web.struts2.CrudActionSupport;
import org.lop.modules.web.struts2.Struts2Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

/**
 * 测试控制层.
 * 
 * @author 潘瑞峥
 * @date 2013-6-13
 */
@Namespace( "/demo" )
@Results( { @Result( name = CrudActionSupport.RELOAD, location = "demo-version-list.action", type = "redirect" ) } )
public class DemoVersionAction extends CrudActionSupport<DemoVersionEntity, String> {

	private static final long serialVersionUID = 8777905367481776095L;

	@Autowired
	private DemoVersionService demoVersionService;

	@Override
	protected void prepareModel() throws Exception {
		if ( StringUtils.isNotBlank( id ) ) {
			entity = this.demoVersionService.get( id );
		} else {
			entity = new DemoVersionEntity();
		}
	}

	@Override
	public String json() throws Exception {
		logger.debug( "json..." );

		List<QueryFilter> filters = QueryFilterHandler.createFilter();

		Page<DemoVersionEntity> page = this.demoVersionService.findPage( pageable, filters );
		Struts2Utils.renderJson( page );

		return null;
	}

	@Override
	public String list() throws Exception {
		throw new UnsupportedOperationException( "list操作暂未支持" );
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		if ( null != entity.getVersion() && workingVersion < entity.getVersion() ) {
			throw new StaleStateException( "对象已有新的版本" );
		}
		this.demoVersionService.save( entity );
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		this.demoVersionService.delete( id );
		return RELOAD;
	}

}